const db = uniCloud.database()
const dbCmd = db.command
const {
	uniIdScoresCollection
} = require('../../../common/constants')
const {
	ERROR
} = require('../../../common/error')

/**
 * 分页查询积分信息
 * @param {Object}  params
 * @param {String}  params.user_id     		用户id
 * @param {String}  params.type     		积分类型 1:收入 2:支出
 * @param {String}  params.begin_date  		查询开始时间
 * @param {String}  params.end_date  		查询结束时间
 * @param {String}  params.start_num  		跳过N条记录
 * @param {String}  params.page_num  		查询记录数
 */
module.exports = async function(params = {}) {
	const schema = {
		user_id: 'string',
		type: {
			required: false,
			type: 'number'
		},
		begin_date: {
			required: false,
			type: 'number'
		},
		end_date: {
			required: false,
			type: 'number'
		},
		start_num:{
			required: true,
			type: 'number'
		},
		page_num:{
			required: true,
			type: 'number'
		}
	}
	this.middleware.validate(params, schema)
	const {
		user_id,
		type,
		begin_date,
		end_date,
		start_num,
		page_num
	} = params

	let reqParams = {
		user_id: user_id
	}
	if (type !== undefined) {
		reqParams.type = type
	}
	if (begin_date !== undefined && end_date !== undefined) {
		reqParams.create_date = dbCmd.and(dbCmd.gt(begin_date), dbCmd.lt(end_date))
	} else if (begin_date !== undefined) {
		reqParams.create_date = dbCmd.gt(begin_date)
	} else if (end_date !== undefined) {
		reqParams.create_date = dbCmd.lt(end_date)
	}

	const resp = await uniIdScoresCollection.where(reqParams)
		.orderBy("create_date", 'desc')
		 // 跳过前N条
		.skip(start_num)
		 // 获取N条
		.limit(page_num)
		.get()
	const userRecord = resp && resp.data ? resp.data : []
	return {
		errCode: 0,
		userRecord: userRecord
	}
}